package thread;

/**
 * 死锁
 * 当多个线程都各自持有一个锁的同时,还等待对方先释放锁,就会形成一种僵持状态,这个就是死锁
 */
public class DeadLockDemo {
    static Object chopsticks = new Object();//筷子
    static Object spoon = new Object();//勺 调羹
    public static void main(String[] args) {
        Thread bf = new Thread() {
            @Override
            public void run() {
                try {//crtl+alt+L快速整理代码格式
                    System.out.println("北方人准备吃饭...");
                    synchronized (chopsticks) {//抢筷子,不释放筷子,别的线程拿不到筷子
                        System.out.println("北方人拿筷子,开始吃饭");
                        Thread.sleep(5000);
                        System.out.println("北方人吃完了饭,去拿勺");
                        synchronized (spoon){//抢勺
                            System.out.println("北方人拿勺,开始喝汤");
                            Thread.sleep(5000);
                            System.out.println("北方人喝完了汤");
                        }
                        System.out.println("北方人放下勺");
                    }
                    System.out.println("北方人放下筷子,吃饭完毕!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread nf = new Thread() {
            @Override
            public void run() {
                try {//crtl+alt+L快速整理代码格式
                    System.out.println("南方人准备吃饭...");
                    synchronized (spoon) {//抢勺
                        System.out.println("南方人拿勺,开始喝汤");
                        Thread.sleep(5000);
                        System.out.println("南方人喝完了汤,去拿筷子");
                        synchronized (chopsticks){//抢筷子
                            System.out.println("南方人拿起筷子,开始吃饭");
                            Thread.sleep(5000);
                            System.out.println("南方人吃完了饭");
                        }
                        System.out.println("南方人放下筷子");
                    }
                    System.out.println("南方人放下勺,吃饭完毕!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        nf.start();
        bf.start();
    }
}
